using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace C4F.DevKit.P2PPictureShare.PictureShareWpf
{
    // Responsible for managing the picture share cache.
    class PictureShareCacheManager
    {
        string _cachePath = string.Empty;

        public PictureShareCacheManager(string cachePath)
        {
            if (cachePath == null)
            { throw new ArgumentNullException("cachePath"); }
            // Cache path is created when needed.
            if (!Directory.Exists(cachePath))
            { Directory.CreateDirectory(cachePath); }

            this._cachePath = cachePath;
        }

        // Save a picture stream to a provided file name.
        public void Save(Stream pictureStream, string pictureName)
        {
            // Construct image from the provided stream.
            Image pic = Bitmap.FromStream(pictureStream);

            // Construct full picture filename.
            // Note: assuming JPEG image.
            string picFullPath = Path.Combine(this._cachePath, pictureName);
            picFullPath = Path.ChangeExtension(picFullPath, ".jpg");

            if (File.Exists(picFullPath))
            {
                // Save will not overwrite any files.
                return;
            }

            // Perform save to disk drive.
            pic.Save(picFullPath, ImageFormat.Jpeg);
        }
    }
}
